package com.example.testapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhttpActivity extends AppCompatActivity implements View.OnClickListener {
    //配置编码
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    private static final int GET = 1;
    private static final int POST = 2;
    private Button btn_get_post;
    private TextView tv_result;
    private Button btn_downloadfile;
    private Button btn_get_okhttputils;
    private Button btn_image;
    private Button btn_image_list;
    private ProgressBar mProgressBar;
    private ImageView iv_icon;
    private OkHttpClient client = new OkHttpClient();
    // 主线程更新UI
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET:
                    // 获取数据
                    tv_result.setText((String) msg.obj);
                    break;
                case POST:
                    // 获取数据
                    tv_result.setText((String) msg.obj);
                    break;

            }
        }
    };

    public OkhttpActivity() {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok);
        btn_get_post = (Button) findViewById(R.id.btn_get_post);
        tv_result = (TextView) findViewById(R.id.tv_result);
        btn_get_okhttputils = (Button) findViewById(R.id.btn_get_okhttputils);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        btn_downloadfile = (Button) findViewById(R.id.btn_downloadfile);
        btn_image = (Button) findViewById(R.id.btn_image);
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        btn_image_list = (Button) findViewById(R.id.btn_image_list);

        btn_get_post.setOnClickListener(this);
        btn_get_okhttputils.setOnClickListener(this);
        btn_downloadfile.setOnClickListener(this);
        btn_image.setOnClickListener(this);
        btn_image_list.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_get_post: // 使用原生okhttp get请求
                tv_result.setText("");
                //getDataFromGet();
                getDataFromPost();
                break;
            case R.id.btn_get_okhttputils:  // 使用okhttp-utils的get
                getDataGetByOkhttpUtils();
                break;
            case R.id.btn_downloadfile:
                downloadFile();
                break;
            case R.id.btn_image:
                getImage(); //请求单张图片
                break;
            case R.id.btn_image_list:
                Intent intent = new Intent(OkhttpActivity.this,OKHttpListActivity.class);
                startActivity(intent);
                break;

        }

    }

    private void getImage() {
        tv_result.setText("");
        String url = "http://192.168.0.105:8080/example/icon.jpg";
        OkHttpUtils.get().url(url).tag(this).build().connTimeOut(20000).readTimeOut(20000)
                .writeTimeOut(20000).execute(new BitmapCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                tv_result.setText("onError:" + e.getMessage());
            }

            @Override
            public void onResponse(Bitmap bitmap, int id) {
                Log.e("TAG", "onResponse：complete");
                iv_icon.setImageBitmap(bitmap);

            }
        });
    }

    // 使用get请求网络数据 子线程 请求接口
    private void getDataFromGet(){
        new Thread(){
            @Override
            public void run(){
                super.run();
                try{
                    String result = get("http://192.168.0.105:8080/example/okhttp.json");
                    Log.e("Tag",result);
                    Message msg = Message.obtain();
                    msg.what = GET;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    // 使用post请求网络请求
    private void getDataFromPost(){
        new Thread(){
            @Override
            public void run(){
                super.run();
                try {
                    String result = post("http://192.168.0.105:8080/example/okhttp.json","");
                    Log.e("TAG",result);
                    Message msg = Message.obtain();
                    msg.what = POST;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    // 使用okhttp-utils的get请求网络文本数据
    private void getDataGetByOkhttpUtils(){
        String url = "http://192.168.0.105:8080/example/okhttp.json";
        // url="http://www.391k.com/api/xapi.ashx/info.json?key=bd_hyrzjjfb4modhj&size=10&page=1";
        OkHttpUtils.get().url(url).id(100).build().execute(new MyStringCallback());

    }
    public void getDataPostByOkhttpUtils() {
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";

        OkHttpUtils
                .post()
                .url(url)
                .id(100)
                .build()
                .execute(new MyStringCallback());
    }
    // 使用okhttp-utils的下载文件
    public void downloadFile(){
        String url = "http://192.168.0.105:8080/example/test.mp4";
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Log.e("TAG",path); // /storage/emulated/0/okhttp-utils-text.mp4
        OkHttpUtils.get().url(url).build().execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(),"okhttp-utils-text.mp4")
        {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("TAG","onError:" + e.getMessage());

            }
            @Override
            public void inProgress(float progress, long total, int id)
            {
                mProgressBar.setProgress((int) (100 * progress));
                Log.e("TAG", "inProgress :" + (int) (100 * progress));
            }

            @Override
            public void onResponse(File file, int id) {
                Log.e("TAG", "onResponse :" + file.getAbsolutePath());

            }
        });

    }

    public class MyStringCallback extends StringCallback{
        @Override
        public void onBefore(Request request,int id){
            setTitle("loading...");
        }
        @Override
        public void onAfter(int id) {
            setTitle("Sample-okHttp");
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            tv_result.setText("onError:" + e.getMessage());

        }

        @Override
        public void onResponse(String response, int id) {
            Log.e("Tag","onResponse:complete");
            tv_result.setText("onResponse:" + response);
            switch (id){
                case 100:
                    Toast.makeText(OkhttpActivity.this, "http", Toast.LENGTH_SHORT).show();
                    break;
                case 101:
                    Toast.makeText(OkhttpActivity.this, "https", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
        @Override
        public void inProgress(float progress,long total,int id){
            Log.d("TAG","inprogress" + progress);
            mProgressBar.setProgress((int) (100 * progress));

        }
    }

    //get请求方法
    private String get(String url) throws IOException{
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    // post请求
    private String post(String url,String json) throws IOException{
        RequestBody body = RequestBody.create(JSON,json);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
